package org.oschina.helper.topic.impl;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.annotation.PreDestroy;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.Session;

import org.apache.commons.lang.StringUtils;
import org.oschina.helper.ApplicationHelper;
import org.oschina.helper.JsonHelper;
import org.oschina.helper.activemq.ActiveMQHelper;
import org.oschina.helper.activemq.JmsType;
import org.oschina.helper.topic.AbstractTopicListener;
import org.oschina.helper.topic.ITopicHelper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jms.core.JmsTemplate;
import org.springframework.jms.core.MessageCreator;
import org.springframework.jms.listener.DefaultMessageListenerContainer;
import org.springframework.stereotype.Component;

/**
 * 订阅实现类
 */
@Component
public class TopicHelperImpl implements ITopicHelper {

	private final static Logger logger=LoggerFactory.getLogger(TopicHelperImpl.class);
	
	private boolean inited=false;
	
	@Autowired
	private ActiveMQHelper activeMQHelper;
	
	@Override
	public boolean send(String key, final Object message)
	{
		if(StringUtils.isBlank(key))
			return false;
		
		activeMQHelper.getTemplate(key, JmsType.TOPIC).send(new MessageCreator()
		{
			@Override
			public Message createMessage(Session session) throws JMSException
			{
				return session.createTextMessage(JsonHelper.toJson(message));
			}
		});
		return true;
	}
	
	@Override
	public void init()
	{
		if(inited)
			return;
		inited=true;
			
		try
		{
			initListener();
		}
		catch(Exception e)
		{
			logger.error("jms初始化失败 - ",e);
		}
	}
	
	private final List<DefaultMessageListenerContainer> listeners=new ArrayList<DefaultMessageListenerContainer>();
	/**
	 * 初始化订阅监听
	 * @throws JMSException 
	 */
	public void initListener() throws JMSException
	{
		Map<String, AbstractTopicListener> listeners=ApplicationHelper.getBeansOfType(AbstractTopicListener.class);
		for(AbstractTopicListener listener:listeners.values())
		{
			JmsTemplate jmsTemplate=activeMQHelper.getTemplate(listener.getKey(), JmsType.TOPIC);
			DefaultMessageListenerContainer messageListener=new DefaultMessageListenerContainer();
			messageListener.setDestination(jmsTemplate.getDefaultDestination());
			messageListener.setConnectionFactory(jmsTemplate.getConnectionFactory());
			messageListener.setMessageListener(listener);
			messageListener.initialize();
			messageListener.start();
			this.listeners.add(messageListener);
		}
	}
	
	/**
	 * 停止监听
	 */
	@PreDestroy
	public void stopListener()
	{
		for(DefaultMessageListenerContainer listener:listeners)
			listener.stop();
	}
}